package com.lzj.weather02;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class WeatherMapper extends Mapper<LongWritable, Text, Weather, IntWritable> {
    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        try {
            //替换双引号并按照逗号切割数据
            String[] datas = value.toString().replaceAll("\"", "").split(",");
            if (datas != null && datas.length == 11) {
                //获取数据
                String province = datas[1];
                String city = datas[2];
                String adcode = datas[3];
                String temperature = datas[5];
                String reporttime = datas[9];
                //转换数据格式
                Date date = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").parse(reporttime);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                //创建Weather对象
                Weather weather = new Weather(adcode, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), Integer.parseInt(temperature), province, city);
                //写出数据 Key　Weather Value 温度
                context.write(weather, new IntWritable(Integer.parseInt(temperature)));
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}
